package co.rcantor.dev.siasar.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import co.rcantor.dev.siasar.R;
import co.rcantor.dev.siasar.SIASARActivity;

public class RegistroWebPendientes extends Activity {
	
	private TextView lblpendientes; 
	private TextView lblregistrados;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registroweb);
        
		lblpendientes = (TextView)findViewById(R.id.lblpendientes);
		lblregistrados = (TextView)findViewById(R.id.lblregistrados);
		
		if(AlmacenamientoDatos.isNetworkAvailable(getApplicationContext())){
			registrarPendientes();
		}else{
			AlertDialog.Builder activador = new AlertDialog.Builder(RegistroWebPendientes.this);
			activador.setMessage("Desea activar su conexion a internet?")
    	       .setPositiveButton("IR", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
    	           }
    	       }).setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {	
				public void onClick(DialogInterface dialog, int which) {
					
				}
    	       });
    	AlertDialog alert = activador.create();
    	alert.show();
			
			
		}
	}

	private void registrarPendientes() {
		String FILENAME = "SIASAR-SEND-DATA.txt";
    	String string = "",formulario="";	  
    	String[] registros;
    	String[] tmp_pares;
    	String[] tmp_valores = null;
    	int pendientes=0,registrados=0;
    	FileInputStream fis = null;
    	ProgressDialog progressDialog;
    	progressDialog = new ProgressDialog(RegistroWebPendientes.this);
		try {		    
			File file = new File("/data/data/co.rcantor.dev.siasar/files/"+FILENAME);
			fis = openFileInput(FILENAME);
			byte bt[] = new byte[(int)file.length()];
			int numBytes = fis.read(bt);
			string = new String(bt);
			System.out.println(numBytes);
			
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();		
			
			registros = string.split("\n");
			pendientes = registros.length;
			lblpendientes.setText("Datos pendientes: " + pendientes);
			lblregistrados.setText("Datos registrados: 0");
			
			for (int i = 0; i < registros.length; i++) {
				tmp_pares = registros[i].split("#");
				for (int j = 0; j < tmp_pares.length; j++) {
					if(tmp_pares.length>1){
						tmp_valores = tmp_pares[j].split("&");
						if(tmp_valores.length>1)
							nameValuePairs.add(new BasicNameValuePair(tmp_valores[0],tmp_valores[1]));
						else if(tmp_valores[0]!="")
							formulario = tmp_valores[0];
					}
				}		        
				
				InputStream is = null;
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://www.siasar.org/android_" + formulario + ".php");
//					HttpPost httppost = new HttpPost("http://www.siasar.org/panama_" + formulario + ".php");					
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
				} catch (Exception e) {
					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				String result = null;
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					result = sb.toString();
					if(!result.contains("Error")){
						lblpendientes.setText("Datos pendientes: " + pendientes--);
						lblregistrados.setText("Datos registrados: "+ registrados++);
						progressDialog.setProgress(Math.round(100/(pendientes+1)));
					}						
					is.close();
				} catch (Exception e) {
					Log.e("log_tag", "Error converting result " + e.toString());
				}
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(RegistroWebPendientes.this);
	    	builder.setMessage("DATOS REGISTRADOS EXITOSAMENTE")
	    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	        	finish();
	    	   		    Intent intent = new Intent(RegistroWebPendientes.this,SIASARActivity.class);
	    	   		    startActivity(intent);
	    	           }
	    	       });
	    	AlertDialog alert = builder.create();
	    	alert.show();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
